package com.pgcomb.poweriot.alarmservice.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@ConditionalOnClass(RedisTemplate.class)
@Component
@Slf4j
public class RedisHelper {

    private RedisTemplate redisTemplate;

    private Environment env;

    public RedisHelper(Environment env) {
        this.env = env;
    }

    /**
     *
     * @Description: 序列化操作。
     *
     * @auther: csp
     * @date: 2019/2/24 下午4:50
     * @param redisTemplate
     * @return: void
     *
     */
    @Resource
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        redisTemplate.setKeySerializer(getKeySerializer());
//        redisTemplate.setValueSerializer(getValueSerializer());
        this.redisTemplate = redisTemplate;
    }

    public static RedisSerializer getKeySerializer() {
        return new StringRedisSerializer();
    }

//    public static RedisSerializer getValueSerializer() {
//        return new GenericFastJsonRedisSerializer();
//    }


    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }


    /**
     * 写入缓存
     * 
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 写入缓存设置时效时间
     * 
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 删除对应的value
     *
     * @param key
     */
    public boolean remove(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 批量删除对应的value
     * 
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }


    /**
     * 判断缓存中是否有对应的value
     * 
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 设置缓存失效时间 秒
     * 
     * @param expiredSeconds
     * @return
     */
    public boolean expire(String key, final Long expiredSeconds) {
        return redisTemplate.expire(key, expiredSeconds, TimeUnit.SECONDS);
    }



    /**
     * 集合添加
     * 
     * @param key
     * @param value
     */
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     * 
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 判断集合中是否存在成员
     * 
     * @param key
     * @param member
     * @return
     */
    public Boolean existsMember(String key, Object member) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.isMember(key, member);
    }

    /**
     * 有序集合添加
     * 
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     * 
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }

    /**
     * 分布式锁 一次性设置(单位：秒)
     * 
     * @param key
     * @param value
     * @param expirationTime
     * @return
     */
    public Boolean setNX(String key, String value, long expirationTime) {

        RedisCallback<Boolean> callback = (connection) -> {
            return connection.set(redisTemplate.getKeySerializer().serialize(key),
                    redisTemplate.getValueSerializer().serialize(value),
                    Expiration.from(expirationTime, TimeUnit.SECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT);
        };
        Boolean result = (Boolean) redisTemplate.execute(callback);

        return result;
    }

    /**
     * 每隔指定时间尝试获取分布式锁，获取成功前一直阻塞
     * 
     * @param key
     * @param value
     * @param expirationTime
     *            锁过期时间
     * @return
     */
    public Boolean getLock(String key, String value, long expirationTime, long sleepSecond) {
        while (true) {
            if (setNX(key, value, expirationTime)) {
                return true;
            }
            try {
                Thread.sleep(sleepSecond * 1000);
            } catch (InterruptedException e) {
                log.error("获取redis锁时当前线程被中断：", e);
            }
        }
    }

    /**
     * 分布式锁 一次性清除
     * 
     * @param key
     * @param value
     * @return
     */
    public Boolean releaseLock(String key, String value) {
        // 序列化需要保持一致 key是主键 arg 是值
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end ";

        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<Long>();
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);

        Long result = (Long) redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        return result != null && result.equals(1L);
    }

}
